package com.x.xdweb.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JSONUtil {
	/**
	 * 该方法用于将JSON字符串转换成java对象
	 * 
	 * @param clazz
	 *            java对象的Class对象
	 * @return 转换后的java 对象
	 * @throws IOException
	 */
	public static Object trasformJson2Object(HttpServletRequest request,
			Class clazz) throws IOException {
		BufferedReader in = request.getReader();
		StringBuffer jsonStr = new StringBuffer();
		String str = "";
		while ((str = in.readLine()) != null) {
			jsonStr.append(str);
		}
		if ("".equals(jsonStr.toString())) {
			return null;
		} else {
			JSONObject jSONObject = JSONObject.fromObject(jsonStr.toString());
			return net.sf.json.JSONObject.toBean(jSONObject, clazz);
		}
	}

	/**
	 * 此方法用于将[{},{}]样式的JSON格式字符串数组转换成�?�?的对象集�?
	 * 
	 * @param request
	 * @param parName
	 *            请求的参数名
	 * @param clazz
	 *            要转换的类型
	 * @param regex
	 *            字符串截取标�?
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List trasformJson2ObjectList(HttpServletRequest request,
			Class clazz) throws Exception {
		BufferedReader in = request.getReader();
		StringBuffer jsonStr = new StringBuffer();// 声明jsonStr
		String str = "";
		while ((str = in.readLine()) != null) {
			jsonStr.append(str);
		}
		JSONArray array = JSONArray.fromObject(jsonStr.toString());
		return (List) JSONArray.toCollection(array, clazz);
	}

	/**
	 * 该方法用于将�?组java对象转换成JSON字符�?
	 * 
	 * @param poList
	 *            集合对象
	 * @return JSON字符�?
	 */
	@SuppressWarnings("unchecked")
	public static String getJsonString(List poList) {
		JSONArray jsonArray = JSONArray.fromObject(poList);
		return jsonArray.toString();
	}

	/**
	 * 该方法用于将�?个java对象转换成JSON字符�?
	 * 
	 * @param o
	 *            java对象
	 * @return JSON字符�?
	 */
	public static String getJsonString(Object o) {
		return JSONObject.fromObject(o).toString();
	}
}
